package com.example.myapplication;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

public class MyScrollView extends LinearLayout {
    private static final String TAG = "MyScrollView";

    public MyScrollView(Context context) {
        super(context);
    }

    public MyScrollView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyScrollView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    int oldx, oldy;// 按下时的位置

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.e(TAG, "onTouchEvent" + event.getAction());
        // 在按下的时候记录初始位置
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            oldx = (int) event.getX();
            oldy =(int) event.getY();
        }
        // 在移动2 计算滑动的距离，计算偏移量
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            int currentX = (int) event.getX(); // 当前x的位置
            int currentY = (int) event.getY();
            int deltay = currentY - oldy; // 可能有正，有负int deltax = currentx - oldx;
            int deltax = currentX - oldx;

            int delwigdth = getChildAt(1).getWidth();
            if (deltax < 0 && Math.abs(deltax) > delwigdth) {
                deltax = -delwigdth;
            }
            if(deltax > 0 && getScaleX()-deltax < 0){
                deltax = 0;
            }
            scrollTo(-deltax, 0);
        }
        // 在松开时
        return true;
    }
}
